package com.mr.sell.service;

import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.model.RefundRequest;
import com.lly835.bestpay.model.RefundResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.mr.sell.entity.OrderMaster;
import com.mr.sell.exception.CustomException;
import com.mr.sell.utils.ConstantEnum;
import com.mr.sell.utils.JsonUtil;
import com.mr.sell.utils.MathUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.math.BigDecimal;

/**
 * Class: PayService
 * User (作者):MRui
 * TODO (描述)：
 * Date 2018.09.25 22:45
 */
@Service
@Slf4j
public class PayService {

    @Autowired
    private BestPayServiceImpl bestPayService;

    @Autowired
    private OrderService orderService;
    /**
    * User (作者): MRui
    * TODO (描述)：创建支付
    * Data：2018.09.25 22:47
    */
    public PayResponse create(OrderMaster orderMaster){
        PayRequest payRequest = new PayRequest();
        payRequest.setOpenid(orderMaster.getBuyerOpenid());
        payRequest.setOrderAmount(orderMaster.getOrderAmount().doubleValue());
        payRequest.setOrderId(orderMaster.getOrderId());
        payRequest.setOrderName("微信点餐订单");
        payRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);

        log.info("[微信支付] 发起支付 request={}", JsonUtil.toJson(payRequest));
        PayResponse payResponse = bestPayService.pay(payRequest);
        log.info("[微信支付] 发起支付 response={}",JsonUtil.toJson(payResponse));
        return payResponse;
    }

    /**
    * User (作者): MRui
    * TODO (描述)：支付结果通知
    * Data：2018.09.26 22:51
    */
    public PayResponse notify(String notifyData){
        //1.验证签名
        //2.支付状态
        //3.支付金额
        //4.支付人（下单人==支付人）

        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        log.info("[微信支付] 异步通知，payResponse={}",JsonUtil.toJson(payResponse));
        //查询订单
        OrderMaster orderMaster = orderService.getOrder(payResponse.getOrderId());
        //判断订单是否存在
        if (orderMaster == null){
            log.info("[微信支付] 异步通知，订单不存在，OrderId={}",payResponse.getOrderId());
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_NOT_EXIST);
        }
        //判断金额是否一致
        if (!MathUtil.equals(payResponse.getOrderAmount(),orderMaster.getOrderAmount().doubleValue())){
            log.info("[微信支付] 异步通知，订单金额不一致。orderId={}，微信通知金额={}，系统金额={}",
                    payResponse.getOrderId(),payResponse.getOrderAmount(),orderMaster.getOrderAmount());
            throw new CustomException(ConstantEnum.EXCEPTION_WECHAT_NOTIFY_MONEY_VERIFY_ERROR);
        }
        //修改订单支付状态
        orderService.paidOrder(orderMaster);
        return payResponse;
    }

    /**
    * User (作者): MRui
    * TODO (描述)：退款
    * Data：2018.09.27 21:45
    */
    public RefundResponse refund(OrderMaster orderMaster){
        RefundRequest refundRequest = new RefundRequest();
        refundRequest.setOrderId(orderMaster.getOrderId());
        refundRequest.setOrderAmount(orderMaster.getOrderAmount().doubleValue());
        refundRequest.setPayTypeEnum(BestPayTypeEnum.WXPAY_H5);
        log.info("[微信退款] request={}",refundRequest);
        RefundResponse refundResponse = bestPayService.refund(refundRequest);
        log.info("[微信退款] response={}",JsonUtil.toJson(refundResponse));
        return refundResponse;
    }
}
